package com.ws.lv.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ws.lv.bean.*;
import com.ws.lv.service.*;
import com.ws.lv.util.Res;
import com.ws.lv.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

@Controller
@RequestMapping("/homepage")
public class HomePageController {

    @Autowired
    TypeService typeService;
    @Autowired
    LinkService linkService;
    @Autowired
    RouteService routeService;
    @Autowired
    SlideshowService slideshowService;
    @Autowired
    ThemeService themeService;
    @Autowired
    ImageService imageService;
    @Autowired
    SaveService saveService;
    @Autowired
    Order_infoService order_infoService;
    @Autowired
    UserService userService;


    //去前台首页
    @RequestMapping("/toHomePage")
    public String toHomePage(Model model) {
        System.out.println("去前台首页");
        //获取类别
        List<Type> types = typeService.homeSelectTypes();
        model.addAttribute("types", types);

        //获取轮播图
        List<Route> routes = routeService.selectRouteBySlideshows();
        ArrayList<Integer> route_ids = new ArrayList<>();
        for (Route route : routes) {
            route_ids.add(route.getRoute_id());
        }
        if (route_ids.size() > 0){
            List<Slideshow> slideshows = slideshowService.selectSlideshowByRouteId(route_ids);
            model.addAttribute("slideshows", slideshows);
        }

        //获取主题
        List<Theme> themes = themeService.selectThemeByStates();
        model.addAttribute("themes", themes);
        //获取主题线路
        Map<Integer, List<Route>> themeRoutes = new HashMap<>();
        for (Theme theme : themes) {
            List<Route> routesByTheme = routeService.selectRoutesByThemeId(theme.getTheme_id());
            themeRoutes.put(theme.getTheme_id(), routesByTheme);
        }
        model.addAttribute("themeRoutes", themeRoutes);


        //获取友情链接
        List<Link> links = linkService.homeSelectLinks();
        model.addAttribute("links", links);
        //获取类别路线
        for (Type type : types) {
            List<Route> routesByType = routeService.selectRouteByTypes(type.getType_id());
            model.addAttribute("routesByType" + type.getType_id(), routesByType);
        }


        return "homepage/index";
    }


    //去前台登陆页面
    @RequestMapping("/toHomeLogin")
    public String toHomeLogin() {
        System.out.println("去前台登陆页面");
        return "homepage/login";
    }

    //去前台注册页面
    @RequestMapping("/toRegister")
    public String toRegister() {
        System.out.println("去前台注册页面");
        return "homepage/register";
    }

    //去前台搜索页面
    @RequestMapping("/toRoute_list")
    public String toRoute_list(String route_name, Model model, Integer currentPage) {
        System.out.println("去前台搜索页面");
        PageHelper pageHelper = new PageHelper();//分页帮助类
        if (currentPage == null) {
            pageHelper.startPage(1, 9);
        } else {
            pageHelper.startPage(currentPage, 9);
        }
        List<Route> routes = routeService.selectRouteByName(route_name);
        PageInfo pageInfo = new PageInfo(routes);

        //热门推荐
        List<Route> saveRoutes = routeService.selectRoutesBySavaNumberLimits();
        model.addAttribute("saveRoutes", saveRoutes);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("route_name", route_name);
        model.addAttribute("currentPage", currentPage);
        return "homepage/route_list";
    }

    //去前台线路详情页面
    @RequestMapping("/toRoute_detail")
    public String toRoute_detail(Integer route_id, Model model, HttpServletRequest request) {
        System.out.println("去前台线路详情页面");
        User u = (User) request.getSession().getAttribute("u");
        if (u != null) {
            Save save = saveService.selectSaveByUserIdAndRouteId(u.getUser_id(), route_id);
            if (save == null) {
                model.addAttribute("save", "weishoucang");
            } else {
                model.addAttribute("save", "shoucang");
            }
            Order_info orderInfo = order_infoService.selectOrder_infoByUserIdAndRouteId(u.getUser_id(), route_id);
            if (orderInfo == null) {
                model.addAttribute("order_info", "weidingdan");
            } else {
                model.addAttribute("order_info", "yidingdan");
            }

        }
        //获取线路信息
        Route route = routeService.selectRouteById(route_id);
        model.addAttribute("route", route);
        //获取线路附图
        List<Image> images = imageService.selectImagesByRouteId(route_id);
        model.addAttribute("images", images);
        return "homepage/route_detail";
    }

    //去前台收藏排行榜页面
    @RequestMapping("/toFavoriterank")
    public String toFavoriterank(Model model, Integer currentPage, String route_name, Integer minRoute_price, Integer maxRoute_price) {
        System.out.println("去前台收藏排行榜页面");
        //获取类别
        List<Type> types = typeService.homeSelectTypes();
        model.addAttribute("types", types);

        //获取路线
        PageHelper pageHelper = new PageHelper();//分页帮助类
        if (currentPage == null) {
            pageHelper.startPage(1, 10);
        } else {
            pageHelper.startPage(currentPage, 10);
        }
        model.addAttribute("currentPage", currentPage);
        List<Route> routes = routeService.selectRoutesBySavaNumberDesc(route_name, minRoute_price, maxRoute_price);
        PageInfo pageInfo = new PageInfo(routes);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("route_name", route_name);
        model.addAttribute("minRoute_price", minRoute_price);
        model.addAttribute("maxRoute_price", maxRoute_price);
        return "homepage/favoriterank";
    }

    //去前台个人页面
    @RequestMapping("/toMypage")
    public String toMypage() {
        return "homepage/mypage";
    }

    //前台个人主页去我的收藏页面
    @RequestMapping("/toMyfavorite")
    public String toMyfavorite(Model model, HttpServletRequest httpServletRequest,Integer currentPage) {
        System.out.println("去前台我的收藏页面");
        User u = (User) httpServletRequest.getSession().getAttribute("u");
        if (u!=null){
            PageHelper pageHelper = new PageHelper();//分页帮助类
            if (currentPage == null){
                pageHelper.startPage(1, 5);
            }else {
                pageHelper.startPage(currentPage, 5);
            }
            List<Save> saves = saveService.selectSavesByUserId(u.getUser_id());
            PageInfo pageInfo = new PageInfo(saves);
            model.addAttribute("pageInfo", pageInfo);
            model.addAttribute("currentPage", currentPage);
        }
        return "homepage/myfavorite";
    }

    //去前台个人主页去我的订单页面
    @RequestMapping("/toDingdan")
    public String toDingdan(HttpServletRequest httpServletRequest,Model model) {
        System.out.println("去前台我的订单页面");
        User u = (User) httpServletRequest.getSession().getAttribute("u");
        if (u!=null){
            List<Order_info> orderInfos = order_infoService.selectOrder_infosByUserId(u.getUser_id());
            model.addAttribute("orderInfos",orderInfos);
        }
        return "homepage/dingdan";
    }

    //支付订单
    @RequestMapping("/updateOrder_infoByState")
    public String updateOrder_infoByState(int order_info_id) {
        System.out.println("支付订单");
        int i = order_infoService.updateOrder_infoByState(order_info_id);
        return "redirect:/homepage/toDingdan";
    }

    //去前台分类页面
    @RequestMapping("/toType")
    public String toType(Model model, Integer type_id, Integer currentPage) {
        System.out.println("去前台分类页面");
        model.addAttribute("type_id", type_id);
        //获取类别
        List<Type> types = typeService.homeSelectTypes();
        model.addAttribute("types", types);
        //获取该类别的线路
        PageHelper pageHelper = new PageHelper();//分页帮助类
        if (currentPage == null) {
            pageHelper.startPage(1, 20);
        } else {
            pageHelper.startPage(currentPage, 20);
        }
        List<Route> routes = routeService.selectRoutesByType(type_id);
        PageInfo pageInfo = new PageInfo(routes);
        model.addAttribute("pageInfo", pageInfo);
        return "homepage/type";
    }

    //前台增加订单功能
    @PostMapping("/placeOrder")
    @ResponseBody
    public boolean placeOrder(@RequestParam Integer route_id, HttpServletRequest request) {
        System.out.println("前台增加订单功能");
        User u = (User) request.getSession().getAttribute("u");
        Order_info orderInfo = order_infoService.selectOrder_infoByUserIdAndRouteId(u.getUser_id(), route_id);
        boolean flag;
        if (orderInfo == null) {
            Order_info order_info = new Order_info();
            order_info.setOrder_info_userId(u.getUser_id());
            order_info.setOrder_info_routeId(route_id);
            order_info.setOrder_info_price(routeService.selectRouteById(route_id).getRoute_price());
            int i = order_infoService.insertOrder_info(order_info);
            flag = true;
        } else {
            flag = false;
        }
        return flag;
    }

    //前台路线收藏
    @PostMapping("/saveRoute")
    @ResponseBody
    public boolean saveRoute(HttpServletRequest request, @RequestParam Integer route_id) {
        System.out.println("前台路线收藏");
        User u = (User) request.getSession().getAttribute("u");
        Save saveTest = saveService.selectSaveByUserIdAndRouteId(u.getUser_id(), route_id);
        boolean flag;
        if (saveTest == null) {
            Save save = new Save();
            save.setSave_userId(u.getUser_id());
            save.setSave_routeId(route_id);
            int i = saveService.insertSave(save);
            routeService.updateRouteSaveNumber(route_id);
            flag = true;
        } else {
            int i = saveService.deleteSaveById(saveTest.getSave_id());
            routeService.updateRouteSaveNumberMinus(route_id);
            flag = false;
        }
        return flag;
    }

    //前台个人主页修改个人信息
    @RequestMapping("/updateUser")
    public String updateUser(User user, MultipartFile newUserTx, HttpServletRequest request,Model model){
        System.out.println("前台个人主页修改个人信息");
        User u = (User) request.getSession().getAttribute("u");
        user.setUser_id(u.getUser_id());
        try {
            User newUser = userService.selectUserByUser_name(user.getUser_name());
            if (newUser==null){
                if (newUserTx.getSize() > 0){
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    String suffix = newUserTx.getOriginalFilename().split("\\.")[1];
                    user.setUser_tx(uuid+"."+suffix);
                    System.out.println("更换新头像");
                    newUserTx.transferTo(new File(Res.homeTxFileDir+uuid+"."+suffix));
                    File file = new File(Res.homeTxFileDir+u.getUser_tx());
                    if (file.exists()){
                        file.delete();
                        System.out.println("删除原头像");
                    }
                }else {
                    System.out.println("使用原头像");
                    user.setUser_tx(u.getUser_tx());
                }
            }else {
                if (newUser.getUser_id() == user.getUser_id()){
                    if (newUserTx.getSize() > 0){
                        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                        String suffix = newUserTx.getOriginalFilename().split("\\.")[1];
                        user.setUser_tx(uuid+"."+suffix);
                        System.out.println("更换新头像2");
                        newUserTx.transferTo(new File(Res.homeTxFileDir+uuid+"."+suffix));
                        File file = new File(Res.homeTxFileDir+u.getUser_tx());
                        if (file.exists()){
                            file.delete();
                            System.out.println("删除原头像");
                        }
                    }else {
                        System.out.println("使用原头像2");
                        user.setUser_tx(u.getUser_tx());
                    }
                }else {
                    System.out.println("用户名已存在");
                    return "redirect:/homepage/toMypage";
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        int i = userService.updateUser(user);
        request.getSession().setAttribute("u",user);
        return "redirect:/homepage/toMypage";


    }

    //前台个人中心修改密码页面
    @RequestMapping("/toUpdateUserPass")
    public String toUpdateUserPass(){
        System.out.println("前台个人中心修改密码页面");
        return "homepage/updatePass";
    }

    //前台个人中心修改密码功能
    @RequestMapping("/updateUserPass")
    public String updateUserPass(HttpServletRequest request,String oldPassword, String newPassword){
        System.out.println("前台个人中心修改密码功能");
        User u = (User) request.getSession().getAttribute("u");
        boolean verify = SecurityUtils.verify(oldPassword,u.getUser_pass());
        if (verify){
            String newPass = SecurityUtils.encrypt(newPassword);
            int i = userService.updateUserPass(newPass,u.getUser_id());
        }else {
            return "redirect:/homepage/toUpdateUserPass";
        }
        return "redirect:/user/qiehuan";
    }




}
